package com.ufox.utils;

import cn.hutool.crypto.KeyUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.AlgorithmUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JWTUtils {




    @Value("${sign}")
    private String sign;


    public String  createJWT(String jian,String userId){
        // SHA256withRSA
        byte[] key = sign.getBytes();
        String id = "rs256";
        JWTSigner signer = JWTSignerUtil.createSigner(id,
                // 随机生成密钥对，此处用户可自行读取`KeyPair`、公钥或私钥生成`JWTSigner`
                KeyUtil.generateKeyPair(AlgorithmUtil.getAlgorithm(id)));

        long time = System.currentTimeMillis() + 1000L*40;

        String token = JWT.create()
                .setPayload(jian, userId)
                .setSigner(signer)
                .setExpiresAt(new Date(time))
                .setKey(key)
                .sign();

        return token;
    }

    public  String getPlayload(String token,String key){
        JWT jwt = JWT.of(token);
       return (String)jwt.getPayload(key);
    }

    public  boolean vertify(String token){
        byte[] key = sign.getBytes();
       return JWT.of(token).setKey(key).validate(0);
    }
}
